<template>
    <table>
        <thead>
            <tr>
                <th>
                    <input type="checkbox" v-model="allChecked">
                    全选
                </th>
                <th>编号</th>
                <th>名称</th>
                <th>单价</th>
                <th>数量</th>
                <th>小计</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <template v-for="item in fruitsData" :key="item.id">
                <tr v-if="item.count > 0">
                    <td>
                        <input type="checkbox" v-model="item.checked">
                    </td>
                    <td>{{ item.id }}</td>
                    <td>{{ item.name }}</td>
                    <td>{{ item.price }}</td>
                    <td>
                        <button>-</button>
                        {{ item.count }}
                        <button>+</button>
                    </td>
                    <td>{{ item.count * item.price }}</td>
                    <td><button @click="deleteItem(item)">删除</button></td>
                </tr>
            </template>
        </tbody>
    </table>
    <div>
        <a href="#" @click.prevent>删除选中商品</a>
        <span>已选中{{ checkedTotal }}件商品</span>
    </div>
    <div>选中合计: {{ checkedPriceTotal }}元</div>
    <h4>{{ fruitsData }}</h4>
</template>

<script setup>
import { computed, ref } from 'vue';

const fruitsData = ref([
    { id: 1, name: '苹果', count: 5, price: 4, checked: false },
    { id: 2, name: '苹果', count: 5, price: 4, checked: false },
    { id: 3, name: '苹果', count: 5, price: 4, checked: false },
])
// 【全选】按钮的状态值
const allChecked = computed({
    get() {
        return fruitsData.value.every(item => item.checked);
    },
    set(newValue) {
        if (newValue) {
            // 进入if，需要将所有商品勾选（所有商品的checked改为true）
            fruitsData.value = fruitsData.value.map(item => {
                return {
                    ...item,
                    checked: true
                };
            })
        } else {
            fruitsData.value = fruitsData.value.map(item => {
                return {
                    ...item,
                    checked: false
                };
            })
        }
    }
})
// 统计已选中的数量
const checkedTotal = computed(() => {
    return fruitsData.value.filter(item => item.checked).length;
})
// 统计选中的总价
const checkedPriceTotal = computed(() => {
    return fruitsData.value.reduce((prev, item) => {
        if (item.checked) {
            return item.count * item.price + prev;
        }
        return prev;
    }, 0)
})



</script>

<style scoped></style>